﻿using System;
using YEA.Infrastructure.Gateway;
using YEA.Utilities.Logging.Converter;

namespace YEA.Utilities.Logging
{
    public class Logger : ILog, IDisposable
    {
        public readonly string LOG_KEY_NAME = "logPublisherName";
        private IGatewayFactory _gf;
        private string _publisherName;
        private IPublisher publisher;
        private bool disposed;
        public Logger()
        {
            _publisherName = System.Configuration.ConfigurationManager.AppSettings[LOG_KEY_NAME];
            if ( string.IsNullOrEmpty(_publisherName))
                throw new ApplicationException(string.Format("The logging utility needs to know the endpoint name to send logs to, please enter it in either the app config with key '{0}' or pass the name in the constructor.", LOG_KEY_NAME));
            _gf = new GatewayFactory();
        }
        public Logger(IGatewayFactory gateway, string publisherName)
        {
            _gf = gateway;
            _publisherName = publisherName;
        }
        public Logger(string publisherName) : this( new GatewayFactory(), publisherName)
        {
        }

        ~Logger()
        {
            Dispose(false);
        }
        public void Write(string message, LogType level)
        {
            var sc = new LogToMessageConverter(level);
            if( publisher == null)
                publisher = _gf.GetPublisher(_publisherName, sc.ConvertObjectToMessage);
            publisher.Publish(message);
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        protected virtual void Dispose(bool disposing)
        {
            if (disposing && !disposed)
            {
                _gf.Dispose();
            }
            disposed = true;
            _gf = null;
        }
    }
}
